package com.java.base.processor;

import javax.annotation.processing.Completion;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Set;

public class XProcessor implements Processor {


    @Override
    public Set<String> getSupportedOptions() {
        return Collections.emptySet();
    }

    @Override
    public Set<String> getSupportedAnnotationTypes() {
        return Collections.singleton("*");
    }

    @Override
    public SourceVersion getSupportedSourceVersion() {
        return SourceVersion.latest();
    }

    @Override
    public void init(ProcessingEnvironment processingEnv) {
        System.out.println(processingEnv.getOptions().toString());
    }

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        try {
            File file = new File("process.txt");
            if (!file.exists()) {
                if (file.createNewFile()) {
                    System.out.println("File can't be created");
                }
            }
            FileOutputStream fileOutputStream = new FileOutputStream(file, true);
            StringBuilder sb = new StringBuilder();
            if (annotations.size() != 0) {
                sb.append("所有注解：\r\n\t");
                annotations.forEach(typeElement -> sb.append(typeElement.getQualifiedName().toString()).append("\r\n\t"));
            }
            sb.append("\r\n");
            roundEnv.getRootElements().forEach(element -> {
                sb.append(element.getSimpleName().toString()).append(":\r\n\t");
                element.getAnnotationMirrors().forEach(annotationMirror -> sb.append(annotationMirror.getAnnotationType().toString()).append("\r\n\t"));
                sb.append("\r\n");
            });
            if (sb.length() != 0) {
                fileOutputStream.write(sb.toString().getBytes(StandardCharsets.UTF_8));
            }
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public Iterable<? extends Completion> getCompletions(Element element, AnnotationMirror annotation, ExecutableElement member, String userText) {
        return Collections.emptyList();
    }
}
